package com.msos.servlet.GetAccountServlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.msos.model.customer.Customer;
import com.msos.model.respBean.RespBean;
import com.msos.service.GetAccountService.GetAccountService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: GetAccountServlet
 * @Description: TODO
 * @Author: hsx
 * @Date: 2022/4/12 22:00
 * @Version: v1.0
 */
@WebServlet(urlPatterns = "/getaccount")
public class GetAccountServlet extends HttpServlet {
    GetAccountService getAccountService = new GetAccountService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if ("page".equals(action)) {
            req.getRequestDispatcher("/WEB-INF/jsp/getAccount/getAccount.jsp").forward(req, resp);
        } else if ("data".equals(action)) {
            Customer c = (Customer) req.getSession().getAttribute("loginCustomer");
            Customer customer = getAccountService.getAccount(c);
            List<Customer> list = new ArrayList<>();
            list.add(customer);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(new ObjectMapper().writeValueAsString(list));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        Customer customer = getAccountService.getAccountByUP(phone, password);
        RespBean respBean = null;
        if (customer == null){
            respBean = RespBean.error("用户不存在或密码错误！");
        }else {
            respBean = RespBean.ok(customer.getBalance().toString());
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(new ObjectMapper().writeValueAsString(respBean));
    }
}
